<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
    @cancel="handleCancel"
    :cancelText="$t('关闭')"
  >
    <template slot="footer">
      <a-row :gutter="20">
        <a-col :span="24">
          <span style="float: left; font-weight: bolder"> </span>
          <a-button type="primary" v-if="state == 0" @click="handleOk(0)">{{ $t('暂存') }}</a-button>
          <a-button type="primary" v-if="state != 1" @click="handleSubmit">{{ $t('盘点') }}</a-button>
          <a-button @click="handleCancel">{{ $t('取消') }}</a-button>
        </a-col>
      </a-row>
    </template>
    <div>
      <a-row style="margin-bottom: 20px">
        <a-col :span="24">
          <a-button v-if="model.id" type="primary" @click="handleExportXls($t('盘点单明细'))">{{
            $t('导出')
          }}</a-button>
          <a-button v-if="model.id" type="primary" @click="printReport" style="margin-left: 8px">{{
            $t('打印')
          }}</a-button>
        </a-col>
      </a-row>
      <div>
        <div style="display: flex; margin-bottom: 20px">
          <div style="width: 40%">
            {{ $t('盘点仓库:') }}
            <j-tree-select
              v-if="state != 1 && state != 2"
              :placeholder="$t('请选择')"
              v-model="model.store"
              dict="bis_goods_store,name,id"
              pid-field="pid"
              @change="getGoodsList(true)"
              pidValue="0"
              hasChildField="has_child"
              style="width: 60%"
            ></j-tree-select>
            <span v-if="state == 1 || state == 2">
              {{ model.store_dictText }}
            </span>
          </div>
          <div v-if="state != 1 && state != 2" style="width: 40%">
            {{ $t('商品分类') }}:
            <a-tree-select
              allowClear
              v-model="model.goodsId"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="treeData"
              :placeholder="$t('请选择')"
              style="width: 60%"
            />
          </div>
          <a-button v-if="state != 1 && state != 2" type="primary" @click="searchHandle()" icon="search">{{ $t('查询') }}</a-button>
        </div>
        <div v-if="state != 1 && state != 2" style="margin: 10px; font-size: 14px; font-weight: bold">
          {{ $t('商品列表') }}：
        </div>
        <a-table
          :columns="columns"
          :dataSource="dataSource"
          size="middle"
          bordered
          class="j-table-force-nowrap"
          :pagination="false"
          style="padding-left: 11px"
          :customRow="customRow"
        >
          <template slot="action" slot-scope="text, record">
            <a-icon type="close" @click="deleteGoods(text, record)" />
          </template>
          <template slot="selectGoods" slot-scope="text, record">
            <span v-if="state == 1 || state == 2">{{ record.goodsId_dictText }}</span>
            <a-select
              v-else
              v-model="record.goodsId"
              show-search
              :placeholder="$t('请选择商品')"
              :filter-option="false"
              :not-found-content="null"
              @search="searchGoods"
              style="width: 100%"
            >
              <a-select-option
                v-for="(good, index) in addGoodsList"
                :key="index"
                :value="good.goodsId"
                @click="changeGoods(record, good)"
                >{{ good.goodsId_dictText }}</a-select-option
              >
            </a-select>
          </template>
          <template slot="actualStock" slot-scope="text, record, index">
            <a-input-number v-model="record.actualStock" @change="changActualStock(record, index)"></a-input-number>
          </template>
          <template slot="comment" slot-scope="text, record">
            <a-input v-model="record.comment"></a-input>
          </template>
        </a-table>
        <div style="margin-top: 20px; font-weight: bolder">
          {{ $t('备注') }}：
          <a-input
            v-if="state != 1 && state != 2"
            style="width: 300px"
            v-model="model.comment"
            :placeholder="$t('请输入备注')"
          />
          <span v-if="state == 1 || state == 2">{{ model.comment }}</span>
        </div>
      </div>
      <goods-inventory-submit ref="modelForm" @ok="submitCallback"></goods-inventory-submit>
      <goods-print-modal ref="printModal"></goods-print-modal>
    </div>
  </j-modal>
</template>

<script>
import { httpAction, getAction, downFile } from '@/api/manage'
import GoodsInventorySubmit from './GoodsInventorySubmit'
import GoodsPrintModal from './GoodsPrintModal'
let that
export default {
  name: 'GoodsInventoryModal',
  components: {
    GoodsInventorySubmit,
    GoodsPrintModal,
  },
  data() {
    return {
      title: '',
      width: 1250,
      visible: false,
      disableSubmit: false,
      model: {
        store: '',
      },
      treeData: [],
      allChildKind: [],
      columns: [],
      columns1: [
        {
          title: '+',
          dataIndex: 'action',
          align: 'center',
          width: 40,
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '25px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
              on: {
                click: () => {
                  that.addGoods()
                },
              },
            }
          },
          customCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '16px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
            }
          },
          scopedSlots: { customRender: 'action' },
        },
        {
          title: this.$t('序号'),
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          width: 36,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: this.$t('商品编码'),
          dataIndex: 'goodsCode',
          align: 'center',
          width: 90,
        },
        {
          title: this.$t('商品名称'),
          dataIndex: 'goodsId',
          align: 'center',
          width: 250,
          scopedSlots: { customRender: 'selectGoods' },
        },
        {
          title: this.$t('成本'),
          key: 'unitPrice',
          dataIndex: 'unitPrice',
          align: 'center',
          width: 80,
          customRender: (t, r) => {
            if (!t && t !== 0) {
              return '0.00'
            }
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('系统数量'),
          key: 'systemStock',
          dataIndex: 'systemStock',
          width: 80,
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          scopedSlots: { customRender: 'systemStock' },
        },
        {
          title: this.$t('系统金额'),
          key: 'systemAmount',
          dataIndex: 'systemAmount',
          align: 'center',
          width: 90,
          customRender: (t, r) => {
            if (!t && t !== 0) {
              return '0.00'
            }
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('实盘数量'),
          key: 'actualStock',
          dataIndex: 'actualStock',
          width: 80,
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          scopedSlots: { customRender: 'actualStock' },
        },
        {
          title: this.$t('实盘金额'),
          dataIndex: 'actualAmount',
          align: 'center',
          width: 90,
          customRender: (t, r) => {
            if (!t && t !== 0) {
              return '0.00'
            }
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('差异'),
          key: 'error',
          dataIndex: 'error',
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          scopedSlots: { customRender: 'error' },
        },
        {
          title: this.$t('差异金额'),
          key: 'errorAmount',
          dataIndex: 'errorAmount',
          align: 'center',
          width: 90,
          customRender: (t, r) => {
            if (!t && t !== 0) {
              return '0.00'
            }
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('备注'),
          key: 'comment',
          dataIndex: 'comment',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'comment' },
        },
      ],
      columns2: [
        {
          title: this.$t('序号'),
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          width: 36,
          customRender: function (t, r, index) {
            if (r.goodsId) {
              return parseInt(index) + 1
            }
            return ''
          },
        },
        {
          title: this.$t('商品编码'),
          dataIndex: 'goodsCode',
          align: 'center',
          width: 100,
        },
        {
          title: this.$t('商品名称'),
          dataIndex: 'goodsId',
          align: 'center',
          width: 250,
          scopedSlots: { customRender: 'selectGoods' },
        },
        {
          title: this.$t('成本'),
          key: 'unitPrice',
          dataIndex: 'unitPrice',
          align: 'center',
          width: 80,
          customRender: (t, r) => {
            if (!t && t !== 0) {
              return '0.00'
            }
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('系统数量'),
          key: 'systemStock',
          dataIndex: 'systemStock',
          width: 80,
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('系统金额'),
          key: 'systemAmount',
          dataIndex: 'systemAmount',
          align: 'center',
          width: 90,
          customRender: (t, r) => {
            if (!t && t !== 0) {
              return '0.00'
            }
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('实盘数量'),
          key: 'actualStock',
          dataIndex: 'actualStock',
          width: 80,
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('实盘金额'),
          dataIndex: 'actualAmount',
          align: 'center',
          width: 90,
          customRender: (t, r) => {
            if (!t && t !== 0) {
              return '0.00'
            }
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('差异'),
          key: 'error',
          dataIndex: 'error',
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('差异金额'),
          key: 'errorAmount',
          dataIndex: 'errorAmount',
          align: 'center',
          width: 90,
          customRender: (t, r) => {
            if (!t && t !== 0) {
              return '0.00'
            }
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('备注'),
          key: 'comment',
          dataIndex: 'comment',
          align: 'center',
          width: 100,
        },
      ],
      url: {
        add: '/goods/bisGoodsInventory/add',
        edit: '/goods/bisGoodsInventory/edit',
        exportXlsUrl: '/goods/bisGoodsInventory/detailExportXls',
      },
      dataSource: [],
      addGoodsList: [],
      state: '',
    }
  },
  created() {
    that = this
  },
  methods: {
    add() {
      that.visible = true
      that.dataSource = []
      that.edit()
    },
    edit(record, state) {
      if (state == undefined) {
        that.state = 0
        that.columns = that.columns1
      } else {
        that.state = state
        that.columns = that.columns2
      }
      that.visible = true
      that.model = Object.assign({}, record)
      that.select()
      if (record) {
        that.getOrderDetail()
      }
    },
    addGoods() {
      if (that.model.store == '' || that.model.store == undefined) {
        that.$message.warning(that.$t('请选择要盘点的仓库'))
        return
      } else {
        let obj = {
          goodsId_dictText: '',
          goodsCode: '',
          systemStock: 0,
          actualStock: 0,
          error: 0,
          systemAmount: 0,
          actualAmount: 0,
          errorAmount: 0,
          comment: '',
        }
        that.dataSource.push(obj)
      }
    },
    getOrderDetail() {
      that.dataSource = []
      getAction('/goods/bisGoodsInventory/queryBisGoodsInventoryDetailsByMainId', { id: that.model.id }).then((res) => {
        let arr = [],
          total = {
            goodsId_dictText: that.$t('合计'),
            unitPrice: 0,
            systemStock: 0,
            actualStock: 0,
            error: 0,
            systemAmount: 0,
            actualAmount: 0,
            errorAmount: 0,
          }
        res.result.forEach((col) => {
          let dtl = {
            goodsId: col.goodsId,
            goodsId_dictText: col.goodsId_dictText,
          }
          arr.push(dtl)
          let aa = {}
          aa = col
          aa.goodsCode = col.goodsCode
          aa.goodsId_dictText = col.goodsId_dictText
          if (that.state == 1) {
            total.unitPrice += col.unitPrice
            total.systemStock += col.systemStock
            total.actualStock += col.actualStock
            total.error += col.error
            total.systemAmount += col.systemAmount
            total.actualAmount += col.actualAmount
            total.errorAmount += col.errorAmount
          }
          that.dataSource.push(aa)
        })
        if (that.state == 1) {
          that.dataSource.push(total)
        }
        that.addGoodsList = arr
      })
    },
    getGoodsList(state) {
      if (state) {
        if (that.dataSource.length > 0) {
          that.$confirm({
            title: that.$t('提示'),
            content: that.$t('切换仓库将清空商品列表，确定要切换吗？'),
            okText: that.$t("确定"),
            cancelText: that.$t("取消"),
            onOk() {
              that.dataSource = []
              return
            },
            onCancel() {},
          })
        }
      }
      let querydata = {}
      querydata.pageNo = 1
      querydata.pageSize = 10
      querydata.parentKindId = that.model.goodsId
      querydata.storeId = that.model.store
      getAction('/goods/bisGoodsStock/list', querydata).then((res) => {
        if (res.success) {
          that.addGoodsList = res.result.records
        }
      })
    },
    searchHandle(value) {
      if (that.model.store == undefined) {
        that.$message.warning(that.$t('请选择要盘点的仓库'))
        return
      }
      let querydata = {}
      querydata.pageNo = 1
      querydata.pageSize = 9999
      querydata.parentKindId = that.model.goodsId
      querydata.storeId = that.model.store
      querydata.goodsInfo = value
      getAction('/goods/bisGoodsStock/list', querydata).then((res) => {
        if (res.success) {
          let arr = []
          res.result.records.forEach((col) => {
            let aa = {
              goodsId: col.goodsId,
              goodsId_dictText: col.goodsId_dictText,
              goodsCode: col.goodsCode,
              systemStock: col.stock,
              actualStock: col.stock,
              error: 0,
              comment: '',
              unitPrice: col.cost,
              actualAmount: col.stock * col.cost,
              systemAmount: col.stock * col.cost,
              errorAmount: 0,
            }
            that.dataSource.push(aa)
            let dtl = {
              goodsId: col.goodsId,
              goodsId_dictText: col.goodsId_dictText,
            }
            arr.push(dtl)
          })
          that.addGoodsList = arr
        }
      })
    },
    searchGoods(value) {
      let querydata = {}
      querydata.pageNo = 1
      querydata.pageSize = 9999
      querydata.parentKindId = that.model.goodsId
      querydata.storeId = that.model.store
      querydata.goodsInfo = value
      getAction('/goods/bisGoodsStock/list', querydata).then((res) => {
        if (res.success) {
          that.addGoodsList = res.result.records
        }
      })
    },
    deleteGoods(a, b) {
      that.dataSource.forEach((col) => {
        if (col.goodsId == b.goodsId) {
          let index = that.dataSource.indexOf(col)
          that.dataSource.splice(index, 1)
        }
      })
    },
    changActualStock(record, index) {
      if (record.actualStock == '' || isNaN(record.actualStock)) {
        that.$set(that.dataSource[index], 'error', 0 - record.systemStock)
        that.$set(that.dataSource[index], 'actualAmount', 0)
        that.$set(that.dataSource[index], 'errorAmount', 0 - record.systemAmount)
      } else {
        that.$set(that.dataSource[index], 'error', parseFloat(record.actualStock) - parseFloat(record.systemStock))
        that.$set(that.dataSource[index], 'actualAmount', parseFloat(record.actualStock) * record.unitPrice)
        let errorAmount = parseFloat(record.actualStock) * record.unitPrice - record.systemAmount
        that.$set(that.dataSource[index], 'errorAmount', errorAmount)
      }
      that.$forceUpdate()
    },
    changeGoods(record, good) {
      record.goodsId_dictText = good.goodsId_dictText
      record.goodsCode = good.goodsCode
      record.unitPrice = good.cost
      record.systemStock = good.stock
      record.systemAmount = good.cost * good.stock
      record.actualStock = good.stock
      record.actualAmount = good.cost * good.stock
      record.error = 0
      record.errorAmount = 0
    },
    handleOk(state) {
      if (that.model.store == '' || that.model.store == undefined) {
        that.$message.warning(that.$t('请选择要盘点的仓库'))
        return
      }
      let i = 0
      if (that.dataSource.length == 0) {
        that.$message.warning(that.$t('商品不能为空'))
        return
      }
      that.dataSource.forEach((col) => {
        if (col.goodsId_dictText == '') {
          that.$message.warning(that.$t('商品名称不能为空'))
          return
        }
        i++
      })

      if (i == that.dataSource.length) {
        let query = {}
        query = that.model
        query.bisGoodsInventoryDetailsList = that.dataSource
        query.state = state
        let method = ''
        let url = ''
        if (that.model.id) {
          method = 'put'
          url = that.url.edit
        } else {
          method = 'post'
          url = that.url.add
        }
        httpAction(url, query, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            if (state == 1) {
              that.submitCallback()
            } else {
              that.$emit('ok')
              that.$set(that.model, 'id', res.result.id)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      }
    },
    handleSubmit() {
      let list = []
      that.dataSource.forEach((col) => {
        if (col.error != 0) {
          list.push(col)
        }
      })
      if (list.length != 0) {
        that.$refs.modelForm.edit(list, that.model)
      } else {
        that.$confirm({
          title: that.$t('提示'),
          content: that.$t('盘点操作将按本次的实盘数量更新系统库存，您确定要执行盘点吗？'),
          okText: that.$t("确定"),
          cancelText: that.$t("取消"),
          onOk() {
            that.handleOk(1)
          },
        })
      }
    },
    select() {
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'sort'
      param.order = 'asc'
      getAction('/goods/bisGoodsKind/rootList', param)
        .then((res) => {
          if (res.success) {
            that.allChildKind = []
            if (res.result.records.length > 0) {
              res.result.records.forEach((col) => {
                col.key = '' + col.id
                col.value = '' + col.id
                col.title = '' + col.name
                col.id = '' + col.id
                col.pid = '' + col.pid
                col.hasChild = '' + col.hasChild
                if (col.hasChild != '0') {
                  that.getHasChild(col)
                }
              })
              that.treeData = that.getDataByResult(res.result.records)
            } else {
              that.treeData = []
            }
          } else {
            that.$alert(res.message, that.$t('提示'), {
              confirmButtonText: that.$t('确定'),
              callback: (action) => {},
            })
          }
        })
    },
    getHasChild(record) {
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.form = '1,7'
      query.pid = record.id
      getAction('/goods/bisGoodsKind/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            record.children = that.getDataByResult(res.result.records)
            that.treeData = [...that.treeData]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        if (item.hasChild == 0 && item.key != '0') {
          that.allChildKind.push(item.key)
        }
        return item
      })
    },
    close() {
      that.$emit('close')
      that.visible = false
    },
    submitCallback() {
      that.$emit('ok')
      that.visible = false
    },
    handleCancel() {
      that.close()
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = that.$t('导出文件')
      }
      let param = {}
      param.orderId = that.model.id
      downFile(that.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          that.$message.warning(that.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    printReport() {
      that.$refs.printModal.show(that.model, 4)
    },
    customRow(r, i) {
      return {
        style: {
          fontWeight: r.goodsId ? 400 : 700,
        },
      }
    },
  },
}
</script>